use rbatis::core::db::DBPoolOptions;
use rbatis::rbatis::Rbatis;

use std::str::FromStr;
use uhlc::HLC;
/// current peer information
pub struct Peer {
  /// installation node id
  pub node_id: uuid::Uuid,
  /// current login user
  pub login_user_id: String,

  pub data_dir:String,
  /// Hybrid Logic Clock
  hlc: HLC,
}

impl Peer {
  /// timestamp in HLC format, use for distribute synchronization
  pub fn timestamp(&self) -> String {
    // generate a timestamp
    let timestamp = self.hlc.new_timestamp().to_string();
    timestamp
  }
}

pub async fn peer(pdata_dir:&str) -> Peer {
  let node_id_ = uuid::Uuid::from_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap();
  Peer {
    node_id: node_id_,
    login_user_id: "user:001".into(),
    data_dir:pdata_dir.to_string(),
    // create an HLC with a generated UUID and relying on SystemTime::now()
    hlc: HLC::with_system_time(node_id_.into()),
  }
}

pub async fn rbatis_pool(file_path:&str) -> Rbatis {

  let driver_url = format!("sqlite://{}", file_path);

  println!("link_opt driver_url={}",driver_url);

  let rb = Rbatis::new();
  let mut opts = DBPoolOptions::new();
  opts.max_connections = 10;

  rb.link_opt(&driver_url, opts).await.unwrap();

  rb

}
